package com.kfm.base.thread.day04;

import java.util.concurrent.atomic.AtomicInteger;

public class Demo03 {

    public static void main(String[] args) {
        Object lock = new Object();

        AtomicInteger integer = new AtomicInteger(1);
        Runnable odd = new Runnable() {
            @Override
            public void run() {
                for (;  integer.get()<= 10;) {
                    synchronized (lock){
                        int i = integer.get();
                        if (i % 2 != 0){
                            System.out.println(Thread.currentThread().getName() + " : " + i);
                            integer.getAndIncrement(); // +1
                            System.out.println(Thread.currentThread().getName() +  "唤醒");
                            lock.notifyAll();
                        }else {
                            try {
                                System.out.println(Thread.currentThread().getName() +  "睡了");
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        };

        Runnable even = new Runnable() {
            @Override
            public void run() {
                for (;  integer.get()<= 10;) {
                    synchronized (lock){
                        int i = integer.get();
                        if (i % 2 == 0){
                            System.out.println(Thread.currentThread().getName() + " : " + i);
                            integer.getAndIncrement(); // +1
                            System.out.println(Thread.currentThread().getName() +  "唤醒");
                            lock.notifyAll();
                        }else {
                            try {
                                System.out.println(Thread.currentThread().getName() +  "睡了");
//                                this.wait();
                                lock.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }

            }
        };
        Thread t1 = new Thread(odd, "奇数");

        Thread t2 = new Thread(even, "偶数");

        t1.start();
        t2.start();
    }
}
